package com.iwinding.ladygg.ui.act;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.iwinding.ladygg.R;
import com.iwinding.ladygg.constant.SPConstant;
import com.iwinding.ladygg.net.RequestManager;
import com.iwinding.ladygg.net.callback.AuthorizeCallback;
import com.iwinding.ladygg.net.callback.TokenCallback;
import com.iwinding.ladygg.net.request.AuthorizeReq;
import com.iwinding.ladygg.net.request.TokenReq;
import com.iwinding.ladygg.net.response.AccessTokenRp;
import com.iwinding.ladygg.net.response.AuthorizeRp;
import com.iwinding.ladygg.net.response.LoginRp;
import com.iwinding.ladygg.ui.EasyPermissions;
import com.iwinding.ladygg.utils.NotificationsUtils;
import com.iwinding.ladygg.utils.SPUtils;
import com.iwinding.ladygg.utils.SystemUtil;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

import static com.iwinding.ladygg.utils.MaterialDialogUtils.openMaterialDialog;

/**
 * Created by hezhiyong on 2017/3/13.
 */

public class GuideActivity extends BaseActivity {

    private static int TOKEN = 100;
    private static int MAIN = 200;
    private static final int REQUEST_SDCARD = 999;
    public static int OVERLAY_PERMISSION_REQ_CODE = 1234;

    private MyHandler handler = new MyHandler();
    boolean launcherOnce;
    boolean is_exit;
    boolean is_token_expired;

    private MaterialDialog materialDialog;
    private List<String> permissionsGrantedlist = new ArrayList<>();
    String[] permission = new String[]{
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.BLUETOOTH,
            Manifest.permission.BLUETOOTH_ADMIN,
            Manifest.permission.CAMERA,
            Manifest.permission.CALL_PHONE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE
    };

    @Override
    protected int getLayoutID() {
        return R.layout.icane_activity_launch;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mHead.setVisibility(View.GONE);
        initLauncher();
        getPermissions();
    }

    /**
     * 初始化启动
     */
    private void initLauncher() {
        launcherOnce = SPUtils.getSpPropertyBoolean(mContext, SPConstant.LAUNCHERONCE, false);
        is_exit = SPUtils.getSpPropertyBoolean(mContext, SPConstant.IS_EXIT, false);
        is_token_expired = SPUtils.getSpPropertyBoolean(mContext, SPConstant.IS_TOKEN_EXPIRED, false);
    }


    private void getPermissions() {
        NotificationsUtils.isHasNFpermission(this);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                requestDrawOverLays();
            }
        }, is_token_expired ? 0 : 1000);
//        initAllPermissions();
    }

    //6.0以上申请系统弹窗权限
    @TargetApi(Build.VERSION_CODES.M)
    public void requestDrawOverLays() {
        boolean iscanDrawOverlays = false;
        if (Build.VERSION.SDK_INT >= 23) {
            iscanDrawOverlays = Settings.canDrawOverlays(GuideActivity.this);
        } else {
            // another similar method that supports device have API < 23
            iscanDrawOverlays = false;
        }
        if (iscanDrawOverlays) {
//            Toast.makeText(this, "can not DrawOverlays", Toast.LENGTH_SHORT).show();
            Toast.makeText(this, "Please open your system alert window", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + GuideActivity.this.getPackageName()));
            startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE);
        } else {
            // Already hold the SYSTEM_ALERT_WINDOW permission, do addview or something.
            initAllPermissions();
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == OVERLAY_PERMISSION_REQ_CODE) {
            if (!Settings.canDrawOverlays(this)) {
                // SYSTEM_ALERT_WINDOW permission not granted...
                Toast.makeText(this, "Permission Denieddd by user.Please Check it in Settings", Toast.LENGTH_SHORT).show();
                finish();
//                initAllPermissions();
            } else {
                Toast.makeText(this, "Permission Allowed", Toast.LENGTH_SHORT).show();
                // Already hold the SYSTEM_ALERT_WINDOW permission, do addview or something.
                initAllPermissions();
            }
        }
    }


    @Override
    public void onPermissionsDenied(int requestCode, final List<String> list) {
        super.onPermissionsDenied(requestCode, list);
        if (requestCode == REQUEST_SDCARD) {
            todoPermissionsDenied(mContext, list);
        }
    }

    /**
     * 去重新开启权限
     *
     * @param mContext
     * @param list
     */
    private void todoPermissionsDenied(final Activity mContext, List<String> list) {
        if (list.size() > 0) {
            if (EasyPermissions.somePermissionPermanentlyDenied(mContext, list)) {
                openMaterialDialog(mContext, R.string.go_setting_desc,
                        R.string.go_setting, R.string.string_exit,
                        new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                gotoSettings(mContext);
                            }
                        }, new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                System.exit(0);
                            }
                        }, false);
                return;
            }
            final String[] permisionDenied = list.toArray(new String[list.size()]);
            openMaterialDialog(mContext, R.string.string_open_permission_desc,
                    R.string.string_authorization, R.string.string_exit,
                    new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            requiresPermission(permisionDenied, getString(R.string.string_read_phone_status_permission), REQUEST_SDCARD);
                        }
                    }, new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            System.exit(0);
                        }
                    }, false);
        }
    }

    /**
     * 去设置页面
     *
     * @param mContext
     */
    private void gotoSettings(Activity mContext) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", mContext.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            intent.setAction(Intent.ACTION_VIEW);
            intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            intent.putExtra("com.android.settings.ApplicationPkgName", mContext.getPackageName());
        }
        mContext.startActivity(intent);
        System.exit(0);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> list) {
        super.onPermissionsGranted(requestCode, list);
        permissionsGrantedlist.addAll(list);
        if (requestCode == REQUEST_SDCARD) {
            if (permissionsGrantedlist.size() == permission.length) {
                hasPermission();
            }
        }
    }

    @Override
    protected void hasPermission() {
        if (is_token_expired) {
            initCodeAndToken();
        } else {
            initGuide();
        }
    }


    private void initAllPermissions() {
        if (!hasPermissions(mContext, permission)) {
            materialDialog = new MaterialDialog.Builder(mContext)
                    .content(R.string.string_open_permission_desc)
                    .positiveText(R.string.string_authorization)
                    .canceledOnTouchOutside(false)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            requiresPermission(permission, getString(R.string.string_read_phone_status_permission), REQUEST_SDCARD);
                        }
                    })
                    .negativeText(R.string.string_exit).onNegative(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            System.exit(0);
                        }
                    }).show();
        } else {
            hasPermission();
        }
    }

    private void initGuide() {
        String cookie = SPUtils.getSpPropertyString(this, SPConstant.COOKIE, "");
        if (!launcherOnce) {
            SPUtils.putSpProperty(mContext, SPConstant.LAUNCHERONCE, true);
            initCodeAndToken();
        } else {
            if (is_exit || is_token_expired || TextUtils.isEmpty(cookie)) {
                goLogin();
                return;
            }
            LoginRp loginRp = SystemUtil.getLoginRp(mContext);
            if (loginRp != null && !TextUtils.isEmpty(loginRp.userId)) {
                if (!EMClient.getInstance().isConnected()) {
                    loginEM(loginRp);
                } else {
                    handler.sendEmptyMessage(MAIN);
                }
            } else {
                goLogin();
            }
        }
    }

    private void goLogin() {
        startActivity(new Intent(GuideActivity.this, LoginActivity.class));
        finish();
    }

    /**
     * 获取Token
     */
    private void initCodeAndToken() {
        RequestManager.postAuthorize(new AuthorizeReq(), new AuthorizeCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(AuthorizeRp response, int id) {
                String code = response.code;
                if (!TextUtils.isEmpty(code)) {
                    RequestManager.postAccessToken(new TokenReq(code), new TokenCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {

                        }

                        @Override
                        public void onResponse(AccessTokenRp response, int id) {
                            String access_token = response.access_token;
                            SPUtils.putSpProperty(getApplicationContext(), SPConstant.IS_TOKEN_EXPIRED, false);
                            SPUtils.putSpProperty(getApplicationContext(), SPConstant.TOKEN_STR, access_token);
                            handler.sendEmptyMessage(TOKEN);
                        }
                    });
                }
            }
        });
    }

    void loginEM(final LoginRp loginRp) {
        if (!TextUtils.isEmpty(loginRp.userId)) {
            if (EMClient.getInstance().isLoggedInBefore()) {
                EMClient.getInstance().logout(true);
            }
            EMClient.getInstance().login(loginRp.userId, loginRp.passwrod, new EMCallBack() {//回调
                @Override
                public void onSuccess() {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            EMClient.getInstance().groupManager().loadAllGroups();
                            EMClient.getInstance().chatManager().loadAllConversations();
                            handler.sendEmptyMessage(MAIN);
                        }
                    }).start();
                }

                @Override
                public void onProgress(int progress, String status) {
                }

                @Override
                public void onError(int code, String message) {
                    if (code == 200) {
                        handler.sendEmptyMessage(MAIN);
                        return;
                    }
                    handler.sendEmptyMessage(TOKEN);
                }
            });
        }
    }

    class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == TOKEN) {
                if (launcherOnce) {
                    handler.postDelayed(new Runnable() {
                        public void run() {
                            goLogin();
                        }
                    }, 2000);
                } else {
                    goLogin();
                }
            } else if (msg.what == MAIN) {
                startActivity(new Intent(mContext, MainActivity.class));
                finish();
            }
        }
    }


}
